#!/usr/bin/env python
# -*- coding:utf8 -*-
import datetime
import os,io
from flask import abort,request,render_template,jsonify,flash,redirect,url_for
from . import main
from .models import User,Cate,Post,Comment
from .schemas import UserSchema,CateSchema
from .forms import SignupForm,SigninForm,NewPostForm,NewCommentForm,UserAvatarForm
from flask_login import login_user,logout_user,login_required,current_user
from .. import db,login_manager
from sqlalchemy import func, or_, not_
import uuid
from .decorators import permission_required
from ..cfg.config import SystemSettings

def __get_cate():
    subcate = []
    currentid = ""
    cate = db.session.query(Cate).\
            filter(Cate.status==1,Cate.parent.is_(None)).\
            order_by(Cate.parent,Cate.order).all()
    for m in cate:
        currentid = m.id
        subcate = m.subs
        break
    return cate,subcate,currentid

def __basedata():
    data = {}
    data['title'] = "heblug"
    data['sheme'] = "v2ex"
    data['curr_user'] = current_user
    return data

def __basedata_withcate():
    data = __basedata()
    cate,subcate,currentid = __get_cate()
    data['cate'] = cate 
    data['subcate'] = subcate 
    return data

def __build_index_data():
    data = __basedata()
    cate,subcate,currentid = __get_cate()
    data['cate'] = cate 
    data['subcate'] = subcate 
    data['currentcateid'] = currentid
    ps = db.session.query(Post).\
            filter(Post.status==1,Post.cate_id==data['currentcateid']).\
            order_by(Post.pub_time.desc()).limit(10).all()
    data['post'] = ps
    return data

def __get_user_by_name(name):
    du = db.session.query(User).\
            filter(User.name == name).first()
    return du

@main.route('/')
def index():
    data = __build_index_data()
    #print data
    #print "current_user.avatar" 
    #if current_user.is_authenticated:
    #    print current_user.avatar
    p = data['post'][0]
    print p.author
    print p.author.avatar
    print p.cate
    print dir(p.cate)
    return render_template(data['sheme']+"/main/index.html",data=data)

@main.route('/signup',methods=['GET','POST'])
def signup():
    form = SignupForm()
    data = __basedata() 
    data['form'] = form
    if form.validate_on_submit():
        #print "received post form data"
        du = __get_user_by_name(form.name.data)
        if du:
            flask("你来晚了，你选择的用户名已经注册了！",'danger')
            return render_template(data['sheme']+"/main/signup.html",data=data)
        user = User()
        user.id =str(uuid.uuid1())
        user.name = form.name.data
        user.nick = form.nick.data 
        user.qq = form.qq.data
        user.phone = form.qq.data
        user.mail = form.mail.data
        user.pw = form.pwd.data
        user.avatar = '/static/img/avatar.jpg'
        user.status = 1 
        user.signup_at = datetime.datetime.now()
        user.roles = ""
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('main.signin'))
    return render_template(data['sheme']+"/main/signup.html",data=data)

@main.route('/signin',methods=['GET','POST'])
def signin():
    data = __basedata()
    form = SigninForm() 
    data['form'] = form
    if form.validate_on_submit():
        try:
            user = __get_user_by_name(form.name.data) 
        except Exception ,e:
            print e.message
            user = None

        if user:
            if user.status == 1:
                print user.name
                print form.pwd.data
                print "user.pw:%s" % user.pw
                if user.verify_password(form.pwd.data):
                    login_user(user)
                    next = request.args.get('next')
                    print next
                    return redirect(next or url_for("main.index"))
                else:
                    flash('用户名或密码有误，请核对后重试!','danger')
            else:
                flash('用户已禁止登录，请与管理员联系！.','danger')
        else:
            flash('用户名或密码有误，请核对后重试!','danger')
    return render_template(data['sheme']+"/main/signin.html",data=data)

@login_manager.user_loader
def load_user(user_id):
    r = User.query.get(user_id)
    return r 

@main.route('/signout')
@login_required
def signout():
    logout_user()
    return redirect("/")

@main.route('/newpost',methods=['GET','POST'])
@login_required
def newpost():
    form = NewPostForm()
    data = __basedata_withcate() 
    data['form'] = form
    if form.validate_on_submit():
        try:
            p = Post()
            p.id =str(uuid.uuid1())
            p.title = form.title.data
            p.cate_id = form.cateid.data 
            p.subcate_id = form.subcateid.data
            p.content_html = form.content_html.data
            p.pub_time = datetime.datetime.now() 
            p.update_time = datetime.datetime.now()
            p.author_id = current_user.id 
            p.tags = ""
            p.status = 1
            p.hits = 0
            p.comments = 0
            p.last_comment_authorid = None
            p.last_comment_time = None
            p.up = 0
            p.donw = 0
            db.session.add(p)
            db.session.commit()
        except Exception, e:
            print e
        return redirect("/")
    return render_template(data['sheme']+"/main/newpost.html",data=data)

@main.route('/subcates/<string:cid>')
def subcates(cid):
    data={}
    cl = db.session.query(Cate).\
            filter(Cate.status==1,Cate.parent==cid).\
            order_by(Cate.order).all()
    cs = CateSchema(many=True)
    data['data'] = cs.dump(cl).data
    print data['data']
    return jsonify(data)

@main.route('/post/<string:pid>',methods=['GET','POST'])
def post(pid):
    data = __basedata() 
    p = db.session.query(Post).\
            filter(Post.status==1,Post.id==pid).first()
    form = NewCommentForm()
    if form.validate_on_submit():
        c = Comment()
        c.id =str(uuid.uuid1())
        c.author_id = current_user.id 
        c.post_id = form.post_id.data 
        c.content_html = form.content_html.data
        c.pub_time = datetime.datetime.now() 
        c.update_time = datetime.datetime.now()
        c.status = 1
        db.session.add(c)
        p = Post.query.get(pid)
        p.last_comment_author_name = current_user.name
        p.last_comment_time = datetime.datetime.now()
        db.session.add(p)
        db.session.commit()
        return redirect("/post/"+pid )
    #print p
    #print p.commentlist.all()
    for c in p.commentlist.all():
        print c
    if p:
        p.comments = p.comments +1
        db.session.add(p)
        db.session.commit()

        form.post_id.data = p.id
        data['form'] = form
        data['post'] = p
    return render_template(data['sheme']+"/main/postdetail.html",data=data)

@main.route('/avatar',methods=['GET','POST'])
@login_required
def avatar():
    form = UserAvatarForm()
    data = __basedata() 
    data['form'] = form
    user=current_user
    if form.validate_on_submit():
        try:
            fn = os.path.join(SystemSettings['settings'].get('avatar_abspath') , str(user.id) +'-avatar.png')
            #print fn
            imgpath = SystemSettings['settings'].get('avatar_path') + str(user.id)+'-avatar.png'
            #print imgpath
            #print form.avatar.data
            avatar_perfix = 'data:image/png:base64,'
            index = form.avatar.data.index(',')
            #print index
            #l = len(form.avatar.data)
            data = form.avatar.data[index+1:]
            #print "--------------------------------"
            #print data
            #print "---------------------------------"
            #print data.decode('base64')
            f = io.open(fn,'wb') 
            f.write(data.decode('base64'))
            f.close()
            #lb = len(APP_FOLDER)
            #lfn = len(fn)
            #imgpath = fn[lb:lfn]
            print imgpath
            user.avatar = imgpath 
            db.session.add(user)
            db.session.commit()
            #u = User.query.get(current_user.id)  
            #u.avatar = form.avatar.data
            #db.session.add(u)
            #db.session.commit()
        except Exception, e:
            print e
        return redirect("/")
    return render_template(data['sheme']+"/main/avatar.html",data=data)


